package documentation_logic

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetDocumentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewGetDocumentLogic 查询知识库
func NewGetDocumentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDocumentLogic {
	return &GetDocumentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDocumentLogic) GetDocument(req *types.QueryDocumentReq) (resp *types.QueryDocumentResp, err error) {
	if req.Id <= 0 {
		err = errors.New("invalid document ID")
		l.Logger.Error(err)
		return &types.QueryDocumentResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	var document types.Document
	query := fmt.Sprintf(`SELECT id, title, author, content, component, tags, content_summary, created_at, updated_at 
              FROM %s WHERE id = ?`, l.svcCtx.Config.Mysql.Tables.DocumentationKnowledge)
	err = l.svcCtx.Conn.QueryRowCtx(l.ctx, &document, query, req.Id)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			logx.Errorf("Document not found, id: %v", req.Id)
			return &types.QueryDocumentResp{
				Code:    500,
				Message: "Document not found",
			}, nil
		}
		logx.Errorf("Failed to query document, error: %v", err)
		return nil, err
	}
	logx.Infof("Document retrieved successfully, id: %v", document.Id)
	return &types.QueryDocumentResp{Code: 200, Message: "success", Data: document}, nil
}
